<?php

namespace Kiri\Server\Task;

use Exception;
use Kiri\Server\ServerInterface;

class TaskExecute implements TaskInterface
{


    /**
     * @param string $handler
     * @param mixed $data
     * @param int $dstWorkerId
     * @param callable|null $finishFinishCallback
     * @return void
     * @throws
     */
    public function task(string $handler, mixed $data, int $dstWorkerId = -1, ?callable $finishFinishCallback = null): void
    {
        $array = class_implements($handler, true);
        if (!in_array(OnTaskInterface::class, $array, true)) {
            throw new Exception('Task is not implement OnTaskInterface');
        }
        $server = \Kiri::getDi()->get(ServerInterface::class);

        $server->task([$handler, $data], $dstWorkerId, $finishFinishCallback);
    }


    /**
     * @param string $handler
     * @param mixed $data
     * @param float $timeout
     * @param int $dstWorkerId
     * @return mixed
     * @throws
     */
    public function taskWait(string $handler, mixed $data, float $timeout = 0.5, int $dstWorkerId = -1): mixed
    {
        $array = class_implements($handler, true);
        if (!in_array(OnTaskInterface::class, $array, true)) {
            throw new Exception('Task is not implement OnTaskInterface');
        }
        $server = \Kiri::getDi()->get(ServerInterface::class);

        return $server->taskwait([$handler, $data], $timeout, $dstWorkerId);
    }


    /**
     * @param array $tasks
     * @param float $timeout
     * @return false|array
     */
    public function taskCo(array $tasks, float $timeout = 0.5): false|array
    {
        $server = \Kiri::getDi()->get(ServerInterface::class);

        return $server->taskCo($tasks, $timeout);
    }


    /**
     * @param array $tasks
     * @param float $timeout
     * @return false|array
     */
    public function taskWaitMulti(array $tasks, float $timeout = 0.5): false|array
    {
        $server = \Kiri::getDi()->get(ServerInterface::class);

        return $server->taskWaitMulti($tasks, $timeout);
    }
}
